import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ComponentPropsType } from "../../components/QuestionComponents/index";
import { produce } from "immer";
import cloneDeep from "lodash.clonedeep";
import { nanoid } from "nanoid";
import { getNextSelectedId, insertNewComponent } from "../utlis";
export type ComponentInfoType = {
  fe_id: string; //TODO 后面解释
  type: string;
  title: string;
  isHidden?: Boolean;
  isLock?: Boolean;
  props: ComponentPropsType;
};
export type ComponentStateType = {
  selectedId: string;
  componentList: Array<ComponentInfoType>;
  copiedComponent: ComponentInfoType | null;
};
const INIT_STATE: ComponentStateType = {
  selectedId: "",
  componentList: [],
  //TODO 其他的扩展
  copiedComponent: null,
};
export const componentSlice = createSlice({
  name: "component",
  initialState: INIT_STATE,
  reducers: {
    // 重置所有组件

    resetComponents: (state: ComponentStateType, action: PayloadAction<ComponentStateType>) => {
      // 从 action.payload 中获取 componentList 和 selectedId
      // const { componentList, selectedId } = action.payload;

      // 更新状态的 components 和 selectedId 字段
      // state.components = componentList || [];
      // state.selectedId = selectedId || "";

      // 注意：这里不需要返回任何内容，因为直接修改了 state 对象
      return action.payload;
    },

    // 修改 selectedId
    changeSelectedId: produce((draft: ComponentStateType, action: PayloadAction<string>) => {
      draft.selectedId = action.payload;
    }),
    //添加组件
    addComponent: produce((draft: ComponentStateType, action: PayloadAction<ComponentInfoType>) => {
      const newCompoent = action.payload;
      //基本逻辑封装了组件
      // const { selectedId, componentList } = draft;
      // const index = componentList.findIndex((item) => item.fe_id === selectedId);
      // if (index !== -1) {
      //   //未选中 插入到index后面
      //   draft.componentList.splice(index + 1, 0, newCompoent);
      // } else {
      //   //选中的话放在后面
      //   draft.componentList.push(newCompoent);
      // }
      // draft.selectedId = newCompoent.fe_id;
      insertNewComponent(draft, newCompoent);
    }),
    //修改组件属性
    changeComponentProps: produce(
      (
        draft: ComponentStateType,
        action: PayloadAction<{ fe_id: string; newProps: ComponentPropsType }>
      ) => {
        const { fe_id, newProps } = action.payload;
        const curComp = draft.componentList.find((item) => item.fe_id === fe_id);
        if (curComp)
          curComp.props = {
            ...curComp.props,
            ...newProps,
          };
      }
    ),
    //删除选中组件
    removeSelectComponent: produce((draft: ComponentStateType) => {
      const { componentList = [], selectedId = removeId } = draft;
      //重新计算selectId
      const newSelectedId = getNextSelectedId(selectedId, componentList);
      draft.selectedId = newSelectedId;
      const index = componentList.findIndex((item) => item.fe_id === selectedId);
      componentList.splice(index, 1);
    }),
    //隐藏/显示组件
    changeComponentHidden: produce(
      (draft: ComponentStateType, action: PayloadAction<{ fe_id: string; isHidden: Boolean }>) => {
        const { componentList = [] } = draft;
        const { fe_id, isHidden } = action.payload;
        //重新计算selectId
        let newSelectedId = "";
        if (isHidden) {
          newSelectedId = getNextSelectedId(fe_id, componentList);
        } else {
          newSelectedId = fe_id;
        }
        draft.selectedId = newSelectedId;

        const curComp = componentList.find((item) => item.fe_id === fe_id);
        if (curComp) {
          curComp.isHidden = isHidden;
        }
      }
    ),
    //锁定/解锁
    toggleChangeLock: produce(
      (draft: ComponentStateType, action: PayloadAction<{ fe_id: string }>) => {
        const { componentList = [] } = draft;
        const { fe_id } = action.payload;
        const curComp = componentList.find((item) => item.fe_id === fe_id);
        if (curComp) {
          curComp.isLock = !curComp.isLock;
        }
      }
    ),
    //拷贝当前选中的组件
    copySelectComponent: produce((draft: ComponentStateType) => {
      const { componentList = [], selectedId } = draft;
      const selectComponent = componentList.find((item) => item.fe_id === selectedId);
      if (selectComponent == null) return null;
      draft.copiedComponent = cloneDeep(selectComponent); //深拷贝
    }),
    //粘贴组件
    pasteSelectComponent: produce((draft: ComponentStateType) => {
      const { copiedComponent } = draft;
      if (copiedComponent === null) return;

      //要把fe_id改了
      copiedComponent.fe_id = nanoid();
      //插入组件
      insertNewComponent(draft, copiedComponent);
    }),

    //选中上一个
    selectPreComponent: produce((draft: ComponentStateType) => {
      const { selectedId, componentList } = draft;
      const selectIndex = componentList.findIndex((item) => item.fe_id === selectedId);
      if (selectIndex === -1) return;//未选中组件
      if (selectIndex <= 0) return;//已经选中第一个无法向上
      draft.selectedId = componentList[selectIndex - 1].fe_id;
    }),
    //选中下一个
    selectNextComponent: produce((draft: ComponentStateType) => {
      const { selectedId, componentList } = draft;
      const selectIndex = componentList.findIndex((item) => item.fe_id === selectedId);
      if (selectIndex === -1) return;//未选中组件
      if (selectIndex >= componentList.length - 1) return;//已经选中最后一个无法向下
      draft.selectedId = componentList[selectIndex + 1].fe_id;
    }),
  },
});

export const {
  resetComponents,
  changeSelectedId,
  addComponent,
  changeComponentProps,
  removeSelectComponent,
  changeComponentHidden,
  toggleChangeLock,
  copySelectComponent,
  pasteSelectComponent,
  selectPreComponent,
  selectNextComponent
} = componentSlice.actions;
export default componentSlice.reducer;
